import {fixedCol, snCreateUIDom} from '../../../../hrpub/common/utils/utils';
import CommonAction from './common';
import moment from 'moment';
import {getAppPageConfig} from 'src/hrpub/common/utils/utils';
import {getBusinessInfo, pageTo} from 'nc-lightapp-front';

let businessInfo = getBusinessInfo() || {};

export default class main extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        if(comp.props.use){
            comp.props.use.form('card','card_batch','psninfo_batch', 'newinfo_batch', 'execinfo_batch', 'table_end_info_batch');
            comp.props.use.editTable('list','list_batch','dept','org');
            comp.props.use.search('multiadd','query')
           
        }
    }

    widget = (type) => {
        const {action} = this.comp;
        action.btnAct.handleChangePeople(type)
    }
    didMount = () => {
        if (window.location.href.match('localhost:3006')) {
            window.location.hash = '#/ifr?page=201981516135101';
        }
        this.getLanguage();
        this.blinkApprove();
        let type = pageTo.getUrlParam('type')
        if (type) {
            setTimeout(() => {
                this.widget(type)
            }, 200);
        }
        this.subscribe();
    };

    // 卸载
    willUnMount = () => {
        this.pubSub.unSubscribe('initData');
        this.pubSub.unSubscribe('toAddPage');
        this.pubSub.unSubscribe('saveItemState');
    };


    didUpdate = () => {
    };
    /* 获取当前页面可见高度 */


    // 修复从审批中心进入页面页面闪动问题
    blinkApprove = () => {
        const {props, action} = this.comp;
        const {getUrlParam, dispatch, exam} = props;
        let scene = getUrlParam('scene');
        // let scene = 'approvesce'
        if (!scene && getUrlParam('status')) {
            scene = 'approvesce'
        }
        if (scene === 'approvesce') {
            dispatch({
                type: 'exam/update',
                payload: {
                    cardMode: true,
                    fromApprove: true
                }
            });
        } else {
            dispatch({
                type: 'exam/update',
                payload: {
                    cardMode: false
                }
            });
        }
    };

    // 事件订阅部分
    subscribe = () => {
        const {comp: {action}, pubSub} = this;
        pubSub.subscribe('initData', (...args) => {
            action.table.initData(...args);
        });
        pubSub.subscribe('getWidgetTableData', (...args) => {
            action.table.getWidgetTableData(...args);
        });
        pubSub.subscribe('toAddPage', (...args) => {
            action.formAct.toAddPage(...args);
        });
        pubSub.subscribe('saveItemState', (...args) => {
            action.formAct.saveItemState(...args);
        });
    };

    // 确认查询
    toSearch = () => {
        const {props, action} = this.comp;
        const {search, dispatch} = props;
        action.table.initData({
            queryCondition: search.getQueryInfo('query', true)
        });
        dispatch({
            type: 'exam/update',
            payload: {
                queryCondition: search.getQueryInfo('query', true)
            }
        });
    };
    getTemplateData = async () => {
        const {props} = this.comp;
        const {meta, button, dispatch} = props;
        let res = await props.templateRes;
        dispatch({
            type: 'exam/update',
            payload: {
                context: res.context,
                templateFlag: true
            }
        });
        let template = {};
        Object.assign(
            template,
            {
                ...res.batch_add,
                org: res.org_situation.org,
                dept: res.org_situation.dept,
                formrelation: {
                    ...res.batch_add.formrelation,
                    ...res.org_situation.formrelation,
                    ...res.template.formrelation
                },
                gridrelation: {
                    ...res.batch_add.gridrelation,
                    ...res.org_situation.gridrelation,
                    ...res.template.gridrelation
                }
            },
            res.template
        );

        meta.setMeta(this.processTemplate(template), this.afterGetTemplate());
        button.setButtons(res.button);
    };
    // 当模版获取并设置完成之后的回调函数
    afterGetTemplate = (res) => {
        this.routePage();
        this.getHeight()
        // this.addDefaultSearchData(res);
    };
    getHeight = () => {
        const {props, action} = this.comp;
        const {dispatch, exam} = props;
        let wH = window.innerHeight,
            domHeight = 0,
            gap = 140;
        domHeight += document.querySelector('header') && document.querySelector('header').clientHeight;
        domHeight += document.querySelector('.ncc-hr-pagination-wrapper')
            ? document.querySelector('.ncc-hr-pagination-wrapper').clientHeight
            : 90;
        console.log(wH, domHeight, gap)
        dispatch({
            type: 'exam/update',
            payload: {
                height: wH - domHeight - gap
            }
        });
    };

    // 给查询弹窗的申请日期添加默认值
    addDefaultSearchData = (res) => {
        res.template['query'].items.forEach((item) => {
            if (item.attrcode === 'apply_date' && !item.initialvalue) {
                let firstValue = moment().date(1).format('YYYY-MM-DD');
                let secondValue = moment().format('YYYY-MM-DD');

                item.initialvalue = {
                    display: `${firstValue},${secondValue}`,
                    value: `${firstValue},${secondValue}`
                };
            }
        });

        return res;
    };
    // 根据url判断是进入到编辑页面还是进入到主页面表格
    routePage = async () => {
        const {props, action} = this.comp;
        const {getUrlParam, dispatch, exam} = props;

        let scene = getUrlParam('scene');
        // let scene = 'approvesce'
        if (!scene && getUrlParam('status')) {
            scene = 'approvesce'
        }
        let id = getUrlParam('id');
        // let status = getUrlParam('status');
        // let id = '1001A4100000000094U3'

        dispatch({
            type: 'exam/update',
            payload: {
                billid: id
            }
        });

        if (scene !== 'approvesce') {
            dispatch({
                type: 'exam/update',
                payload: {
                    cardMode: false
                }
            });
            return;
        }

        await dispatch({
            type: 'exam/update',
            payload: {
                cardMode: true,
                refValue: {
                    refpk: businessInfo.groupId
                },
                fromApprove: true
                // editState:true
            }
		});
		await action.formAct.oneAction(id);
	};
    processTemplate = (template) => {
        const {props, action} = this.comp;
        const {exam, button} = props;

        // 给每个字段添加查询对象
        [
            'card',
            'card_batch',
            'psninfo',
            'oldinfo',
            'newinfo',
            'execinfo',
            'table_end_info',
            'audit_info',
            'psninfo_batch',
            'newinfo_batch',
            'execinfo_batch',
            'table_end_info_batch',
            'query'
        ].forEach((item) => {
            template[item].items.forEach((item) => {
                if (!item.queryCondition) {
                    item.queryCondition = {};
                }
            });
        });

        fixedCol(template['list'], ['transtype', 'approve_state'], exam.json['gx6008-000195']);
        // 给主页面表格每行添加操作按钮
        template['list'].items = template['list'].items.concat([
            {
                itemtype: 'customer',
                label: exam.json['gx6008-000071'] /* 国际化处理： 附件管理*/,
                visible: true,
                fixed: 'right',
                width: '90px',
                hyperlinkflag: false,
                attrcode: 'opr',
                render: (text, record, index) => {
                    return (
                        <div>
							<span style={{color: '#007ace', cursor: 'pointer'}}>
								<i
                                    className="icon iconfont icon-fujianshenpi"
                                    onClick={action.table.enclosure(record, index)}
                                />
							</span>
                        </div>
                    );
                }
            },
            {
                itemtype: 'customer',
                label: exam.json['gx6008-000046'] /* 国际化处理： 操作*/,
                visible: true,
                fixed: 'right',
                width: '290px',
                hyperlinkflag: false,
                attrcode: 'opr',
                render: (text, record, index) => {
                    return (
                        <div>
							<span
                                style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                onClick={action.table.editTableRow(record, index)}
                            >
								{/* 修改 */}
                                {exam.json['gx6008-000038']}
							</span>
                            <span
                                style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                onClick={action.table.copyTableRow(record, index)}
                            >
								{/* 复制 */}
                                {exam.json['gx6008-000040']}
							</span>
                            <span
                                style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                onClick={action.table.viewOpinion(record, index)}
                            >
								{/* 查看审批意见 */}
                                {exam.json['gx6008-000041']}
							</span>
                        </div>
                    );
                }
            }
        ]);
        template['list'].items.forEach((item) => {
            if (item.attrcode === 'bill_code') {
                item.renderStatus = 'browse';
                item.render = (text, record, index) => {
                    return (
                        <span
                            style={{color: '#007ace', cursor: 'pointer', textDecoration: 'underline'}}
                            onClick={action.table.doubleClick(record, false)}
                        >
							{record.values.bill_code.value}
						</span>
                    );
                };
            }
        });

        template['multiadd'].items.forEach((item) => {
            if (item.attrcode === 'hi_psnjob.pk_org' || item.attrcode === 'hi_psnjob.pk_org.code') {
                if (!item.queryCondition) {
                    item.queryCondition = {};
                }
                Object.assign(item.queryCondition, {
                    TreeRefActionExt: 'nccloud.web.hrhi.pub.sqlbuilder.OrgRefSqlBuilder'
                });
            }
        });
        template['dept'].items.forEach((item) => {
            if (item.attrcode === 'budget_leftover') {
                item.width = '160px';
            }
        });

        return template;
    };

    // 获取多语
    getLanguage = () => {
        const {props} = this.comp;
        const {dispatch, MultiInit} = props;

        MultiInit.getMultiLang({
            moduleId: 'gx6008',
            domainName: 'hrtrn',
            callback: (json, status, init) => {
                dispatch({
                    type: 'exam/update',
                    payload: {
                        json: json
                    }
                });
                this.getTemplateData();
            }
        });
    };

    // 翻页
    turnPage = (page) => {
        const {props, action} = this.comp;
        const {exam, dispatch} = props;

        if (page === exam.pageInfo.pageIndex) {
            return;
        }

        let pageInfo = {
            ...exam.pageInfo,
            pageIndex: page
        };
        if (exam.widget) {
            this.pubSub.publish('getWidgetTableData', {
                pageInfo: pageInfo
            });
        } else {
            this.pubSub.publish('initData', {
                pageInfo: pageInfo
            });
        }
    };

    // 改变每页显示条数
    changePageSize = (size) => {
        const {props, action} = this.comp;
        const {exam, dispatch} = props;

        if (size === exam.pageInfo.pageSize) {
            return;
        }

        let pageInfo = {
            ...exam.pageInfo,
            pageSize: size
        };
        if (exam.widget) {
            this.pubSub.publish('getWidgetTableData', {
                pageInfo: pageInfo
            });
        } else {
            this.pubSub.publish('initData', {
                pageInfo: pageInfo
            });
        }
    };

    // 通用关闭弹窗
    closeModal = (field) => {
        return () => {
            const {props} = this.comp;
            const {dispatch, exam} = props;

            dispatch({
                type: 'exam/update',
                payload: {
                    [field]: false
                }
            });
        };
    };
}
